const glSqlEditor = require('w-vue-middle/components/glSqlEditor').default;
const setSourceColumn = require('../setSourceColumn').default;
const $appService = require("w-vue-middle/api/appService");

export default {
  components: {
    glSqlEditor,
    setSourceColumn
  },
  props: {
    sourceColumns: {
      type: Array,
      default: () => {
        return [];
      }
    },
    outputTable: {
      type: Object,
      default: () => {
        return {};
      }
    },
    tableColumns: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  computed: {
    tableList() {
      return this.outputTable.data.mapping.filter((item) => {
        return this.filterOutTableName(item);
      })
    },
  },
  data() {
    return {
      loading: false,
      queryParams: {
        name: undefined,
        notMap: false,
        notNull: false,
      },
      queue: {},
      verifyMapping: {
        verify: 'pass',
        messages: [],
      }, //验证信息
      setColumn: {
        show: false,
        data: {},
      },
      incrementalField: {},
      replacedWords: []
    };
  },
  created() {
    this.getReplacedWord();
  },
  methods: {
    /**
     * @Author: y_zp
     * @description: 更改输入表后，数据处理
     */
    initData(type) {
      this.loading = true;
      this.outputTable.data.mapping.forEach((mapping, index) => {
        this.analysisColumn(false, mapping); //页面数据自动规整
        // 增量字段处理
        this.$set(this.incrementalField, index + 1, "0");

        if (mapping.source.type == 'field' || mapping.source.select) {
          let has = this.sourceColumns.find((column) => {
            let keyName = column.tableAsName || column.tableCode;
            mapping.source.columnName = mapping.source.select;
            return `${keyName}.${column.columnName}` == mapping.source.select;
          });
          if (has) {
            mapping.source.has = '';
          } else {
            mapping.source.has = 'no_source';
          }
        }
      });
      this.loading = false;
      
      if(type == "auto") {
        this.outTablesSmartFill();
      } 
    },
    /**
     * @Author: y_zp
     * @description: 设置增量字段
     */
    changeIncField(row, seq) {
      if(!row.source.select || !row.source.columnName) {
        this.$message.warn("请先设置输入列名");
        this.incrementalField[seq] = "0";
      } else {
        for(let i in this.incrementalField) {
          if( Number(i) != seq ) {
            this.incrementalField[i] = "0";
          }
        }
        if(this.incrementalField[seq] == "1") {
          this.$emit("changeIncField", row.source);
        }
      }
    },

    /**
     * @Author: y_zp
     * @description: 获取替换的关键字
     */
    getReplacedWord() {
      $appService.sysConfigByKey("datatransfer.job.repaired_mapping_keywords").then(req => {
        let info = req.data;
        if(info) {
          this.replacedWords = req.data.split(",").map(item => {
            return item.toLocaleLowerCase();
          });
        }
        
      })
    },

    /**
     * @Author: y_zp
     * @description: 查询设置
     */
    filterOutTableName(row) {
      let nameHas = true;
      if (this.queryParams.name) {
        let tHas = row.target.columnName.indexOf(this.queryParams.name) > -1;
        let sHas = row.source.columnName && row.source.columnName.indexOf(this.queryParams.name) > -1;
        nameHas = tHas || sHas;
      }
      let mapHas = true;
      if (this.queryParams.notMap) {
        mapHas = !row.source.columnName;
      }
      let notNullHas = true;
      if (this.queryParams.notNull) {
        notNullHas = row.target.notNull;
      }
      return nameHas && mapHas && notNullHas;
    },
    /**
     * @Author: y_zp
     * @description: 设置输入字段
     */
    viewSetColumn(row) {
      this.setColumn = {
        show: true,
        data: row
      }
    },
    /**
     * @Author: Jason Liu
     * @description: 分析字段内容
     */
    analysisColumn(e, row) {
      if (!e) {
        let verifyInfo = {
          verify: 'pass',
          messages: [],
        };
        /**
         * @Author: Jason Liu
         * @description: 修改警告状态
         */
        const changeState = () => {
          if (verifyInfo.verify == 'pass') {
            verifyInfo.verify = 'warning';
          }
        };

        const verifyData = () => {
          if (row.source.columnType != row.target.columnType) {
            changeState();
            verifyInfo.messages.push({
              type: 'warning',
              message: $t('输入类型与输出类型不一样，可能会导致调度异常！'),
            });
          }

          if (row.source.columnSize > row.target.columnSize) {
            changeState();
            verifyInfo.messages.push({
              type: 'warning',
              message: $t(
                '输入字段长度大于输出字段长度，输入类型与输出类型不一样，可能会导致调度异常！',
              ),
            });
          }

          let data = row.source.columnName;
          const stringRegex = /^'.*'$/;
          if (!stringRegex.test(data)) {
            //收尾没有'
            if (row.source.columnType == 'TIMESTAMP') {
              //日期格式，需要添加‘
              verifyInfo.messages.push({
                type: 'warning',
                message: $t('日期数据，请前后添加，可能会导致调度异常！'),
              });
            }

            const placeRegex = /^\${.*}$/; //占位符正则
            var funRegex = /\?|[.]|[(]|[)]|[+]|[-]|[_]|[`]/g; //非字符内容的正则

            if (placeRegex.test(data)) {
              verifyInfo.verify = 'error';
              verifyInfo.messages.push({
                type: 'error',
                message: $t('占位符需要添加首位添加 _#_单引号，否则会导致调度异常！'),
              });
            } else if (!funRegex.test(data)) {
              verifyInfo.messages.push({
                type: 'warning',
                message: $t('内容需要首位添加 _#_单引号，否则会导致调度异常！'),
              });
            }
          }
        };

        if (row.source.columnName) {
          let sourceColumn = this.sourceColumns.find((column) => {
            return (
              [
                `${column.tableAsName}.${column.columnName}`,
                `${column.tableAsName}.${column.asName}`,
              ].indexOf(row.source.columnName.trim()) > -1
            );
          });
          if (sourceColumn) {
            if (row.source.lockType) {
              row.source = {
                ...row.source,
                select: row.source.columnName,
                description: sourceColumn.description,
                columnTypeFlink: sourceColumn.columnTypeFlink,
                pk: sourceColumn.pk,
                has: '',
                type: 'field',
              };
            } else {
              row.source = {
                ...row.source,
                select: row.source.columnName,
                columnType: sourceColumn.columnType,
                description: sourceColumn.description,
                columnTypeFlink: sourceColumn.columnTypeFlink,
                columnSize: sourceColumn.columnSize,
                pk: sourceColumn.pk,
                has: '',
                type: 'field',
              };
            }
            verifyData();
          } else {
            let has = '';
            if (row.source.select == row.source.columnName) {
              has = 'no_source';
              changeState();
              verifyInfo.messages.push({
                type: 'warning',
                message: $t('未找到输入列，已自动换行成函数字段，修改后警告去除！'),
              });
            }
            row.source = {
              ...row.source,
              pk: false,
              select: undefined,
              has: has,
              type: 'fun',
            };

            if (!row.source.lockType) {
              let columnType = 'VARCHAR';

              const time = row.source.columnName.replaceAll("'", '');
              if (!isNaN(row.source.columnName)) {
                //fun 数字类型和来源不匹配 1需要是数字            给出警告
                let num = row.source.columnName;
                if (parseInt(num) == parseFloat(num)) {
                  columnType = 'INT';
                } else {
                  columnType = 'DECIMAL';
                }
              } else if (this.moment(time).isValid() && time.length >= 10) {
                columnType = 'TIMESTAMP';
              }

              //fun 占位符类型和来源不匹配 字符需要给单引号      给出报错 NA
              //fun . ( ) 空格 不需要单引号警告，其他给出警告

              row.source = {
                ...row.source,
                description: undefined,
                columnTypeFlink: undefined,
                columnSize: 32,
                columnType: columnType,
              };
            }
            verifyData();
          }
        } else {
          if (row.target.notNull) {
            verifyInfo.verify = 'error';
            verifyInfo.messages.push({
              type: 'error',
              message: $t('非空列，必须设置输入列名信息'),
            });
          }

          row.source = {
            pk: false,
            lockType: false,
            select: undefined,
            description: undefined,
            columnTypeFlink: undefined,
            columnSize: undefined,
            type: undefined,
            columnType: undefined,
          };
        }
        this.verifyMapping[row.target.columnName] = verifyInfo;
      }
    },
    /**
     * @Author: y_zp
     * @description: 自动关联
     */
    outTablesSmartFill() {
      this.outputTable.data.mapping = this.outputTable.data.mapping.map((item) => {
        let sourceColumn = this.sourceColumns.find((column) => {
          return (
            [`${column.columnName.toLocaleLowerCase()}`, `${column.asName}`].indexOf(
              item.target.columnName.toLocaleLowerCase().trim(),
            ) > -1
          );
        });
        if (sourceColumn) {
          let sName = sourceColumn.columnName;
          if(this.replacedWords.indexOf(sName.toLocaleLowerCase()) > -1) {
            sName = '`' + sName + '`';
          }
          item.source = {
            ...sourceColumn,
            columnName: `${sourceColumn.tableAsName || sourceColumn.tableCode}.${ sName }`,
            select: `${sourceColumn.tableAsName || sourceColumn.tableCode}.${ sName }`,
            has: '',
            type: 'field',
          };
          this.verifyMapping[item.target.columnName] = { verify: 'pass', messages: [] }
        } else {
          // 输出表添加的默认字段，需要给默认值
          if(item.target.columnName == "local_table_created_at") {
            item.source = {
              columnName: "cast(now() as varchar)",
              type: "fun",
              has: "",
              columnSize: 64,
              columnType: "VARCHAR",
              description: undefined,
              columnTypeFlink: undefined,
              lockType: false,
              pk: false,
            };
          }
        }
        return item;
      });
    },

    /**
     * @Author: Jason Liu
     * @description: 清空设置内容
     */
    clearColumn(row) {
      row.source.select = undefined;
      row.source.columnName = undefined;
      row.source.lockType = false;
      row.source.columnType = undefined;
      row.source.columnSize = undefined;
    },




  }
};